﻿using System;
using System.Data;
using TimKen.DataEntity;
using System.Collections.Generic;
using TimKen.DataAccess;

namespace TimKen.BussLogic
{
    /// <summary>
    /// 订单集合业务逻辑操作类
    /// </summary>
    public class OrderManager : BaseManager
    {
        private readonly TimKen.DataAccess.OrderDAO dal = new TimKen.DataAccess.OrderDAO();
        private readonly TimKen.BussLogic.ShoppingCartManager scm = new ShoppingCartManager();
        public OrderManager()
        { }
        #region  成员方法
        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(string OrderID)
        {
            return dal.Exists(OrderID);
        }

        /// <summary>
        /// 增加一条数据
        /// </summary>
        public string Add(TimKen.DataEntity.Order model)
        {
            model.OrderID = Guid.NewGuid().ToString();

            //生成订单号
            model.OrderNo = DateTime.Now.ToString("yyyyMMddHHmmsss");
            model.CreateDate = DateTime.Now;


            //添加订单,更新客户的EC已用额度 
            dal.Add(model);
            OrderItemManager orderItemM = new OrderItemManager();
            foreach (OrderItem orderItem in model.OrderItems)
            {
                orderItem.OrderID = model.OrderID;
                orderItemM.Add(orderItem);
            }

           

            //清空购物车
            scm.CleanCart(model.Creator);
            return model.OrderID;
        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public void Update(TimKen.DataEntity.Order model)
        {
            dal.Update(model);
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public void Delete(string OrderID)
        {

            dal.Delete(OrderID);
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public TimKen.DataEntity.Order GetModel(string OrderID, int languageID)
        {

            return dal.GetModel(OrderID, languageID);
        }

        public TimKen.DataEntity.Order GetModel(string OrderID)
        {
            return GetModel(OrderID, 1);
        }

        /// <summary>
        /// 根据SQL拼接语句，获得数据列表
        /// </summary>
        public DataSet GetList(string strWhere)
        {
            return dal.GetList(strWhere);
        }
              /// <summary>
        /// 获取订单详细
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="orderNo"></param>
        /// <returns></returns>
        public DataSet GetOrderDetail(string userName, string orderNo)
        {
            return dal.GetOrderDetail(userName, orderNo);
        }
        /// <summary>
        /// 获得所有数据列表
        /// </summary>
        public DataSet GetAllList()
        {
            return GetList("");
        }

       /// <summary>
        /// 分页获取数据列表，同时支持SQL拼接语句
       /// </summary>
        public DataSet GetList(int PageSize, int PageIndex, string strWhere, string OrderField, bool Direction, int languageID)
        {

            OrderField = OrderField == null ? "OrderNo" : OrderField;
            return dal.GetList(PageSize, PageIndex, strWhere, OrderField, Direction, languageID);
        }



        public TimKen.DataEntity.Order CheckedOrder(string userName)
        {
            //1.数量检验，
            //  循环购物车中的每一项，计算产品的可出货额和购买数量：
            //   |--数量不足-->返回false，提示产品名称+不足信息--||结束
            //   |--数量足够
            //       |--2.信用检查
            //            1)从usererName获取User信息再获取到相应的Customer信息
            //            2)计算出Customer的可用信用额度
            //            3)计算userName获取购物车中的含税总价
            //                |--含税总价<=可用信用额度--->orderState =1 Pass，返回true--||结束
            //                |--含税总价>可用信用额度
            //                    |--4)检查系统设置，是否必须条件
            //                          |--必须-->返回false--||结束 
            //                          |--非必须-->orderState =2 For B1 Check 返回true--||结束 

            ShoppingCartManager cartM = new ShoppingCartManager();
            ProductManager ptM = new ProductManager();

            DataSet cartLists = cartM.GetList(" UserName = '" + userName + "'");
            Order order = new Order();//订单
            List<OrderItem> orderItems = new List<OrderItem>();

            //获取客户信息
            CustomerManager ctmM = new CustomerManager();
            UserAccountManager userM = new UserAccountManager();
            UserAccount user = userM.GetModel(userName);
            Customer customer = ctmM.GetModel(userM.GetModel(userName).CustomerID.Value);
            int maxShipDays = 0;

            foreach (DataRow cart in cartLists.Tables[0].Rows)
            {
                //获取产品
                Product product = ptM.GetModel(int.Parse(cart["ProductID"].ToString()));

                if (product == null)
                    continue;

                if (CheckFrozen(product.Freeze, product.FreezeFrom, product.FreezeTo))
                    continue;

                //客户购买量
                decimal number = decimal.Parse(cart["Number"].ToString());

                //-----检核库存-----
                //商品可用库存




                //2009-3-30 修改成库存为空也可以下单
                //decimal pInv = product.InvQty - product.BookedQty.Value;
                //if (number > pInv)
                //{
                //    ValidMessage = product.ItemCode + GetLangString("NotEnoughInventory");
                //    return null;
                //}




                //-----保存OrderItem-----
                OrderItem orderItem = new OrderItem();

                
                //修改by miaozy at  090305 价格加入多币种
                PPrice price = ptM.GetProductBasePrice(product.ProductID, customer.CustomerID);
                if (price.Price == 0)
                {
                    ValidMessage = GetLangString("Price0Product");
                    return null;
                }

                orderItem.BasicPrice = price.Price;
                orderItem.FinalPrice = ptM.GetProductPriceByCustomer(product, customer.CustomerID, number);
                orderItem.ItemCode = product.ItemCode;
                orderItem.ProductID = product.ProductID;
                orderItem.Quantity = number;

                orderItem.Weight = product.Weight;
                orderItem.WeightUnit = product.WeightUnit;
                orderItem.TotalWeight = product.Weight * number;
                orderItem.BaseAmount = orderItem.FinalPrice * orderItem.Quantity;
                orderItem.Unit = product.SalesUnit;



                ///用BarCode字段来存储产品名称，即产品型号
                PDescriptionManager pdm = new PDescriptionManager();
                PDescription description = pdm.GetModel(product.ProductID, 1);
                orderItem.BarCode = description.Name;



                //在订单单身中添加折扣率
                if (orderItem.BasicPrice != 0)
                    orderItem.Discount = orderItem.FinalPrice / orderItem.BasicPrice;
                else
                    orderItem.Discount = 1;


                if (customer.TaxRate == 0)
                {
                    orderItem.TaxAmount = 0;
                    orderItem.TaxRate = 0;
                }
                else
                {
                    orderItem.TaxAmount = orderItem.BaseAmount * product.TaxRate.Value;
                    orderItem.TaxRate = product.TaxRate.Value;
                }
                orderItem.TotalAmount = orderItem.BaseAmount + orderItem.TaxAmount;
                //-----计算order的未含税总额，含税总额，总税额-----
                order.BaseAmount += orderItem.BaseAmount;
                order.TotalAmount += orderItem.TotalAmount;
                order.TaxAmount += orderItem.TaxAmount;

                orderItems.Add(orderItem);
                maxShipDays = product.ShipDays > maxShipDays ? product.ShipDays : maxShipDays;
            }

            //-----信用检测-----

            //客户可使用信用额度  修改by miaozy
            decimal balance = customer.CreditLimit.Value + customer.CurrentAccountBalance.Value - customer.ECOrdersBalance == null ? 0 : customer.ECOrdersBalance.Value;

            //购物含税总价未超过可使用额度
            bool CheckBefore = SystemConfigManager.SystemConfig.CreditCheck;

            if (order.TotalAmount > balance)
            {
                //信用检测为必要关卡
                if (CheckBefore)
                {
                    order.CheckFlag = false;
                    ValidMessage = GetLangString("NotEnoughAmount");
                    return null;
                }
                else
                {
                    //信用检测非关卡
                    //设置状态为for B1 Check
                    order.OrderStatus = OrderStatus.ForB1Check;
                }
            }
            else
            {
                order.OrderStatus = OrderStatus.Pass;
                //设置状态为Pass

            }
            order.MaxShipDays = maxShipDays;
            order.Currency = customer.Currency;
            order.Rate = customer.TaxRate.Value;
            order.CardCode = customer.CardCode;
            order.ApproveType = CheckBefore ? 1 : 0;
            order.OrderItems = orderItems;
            order.TaxClassID = customer.TaxClassID;
            order.SalesPersonCode = customer.SalesPersonCode;
            order.Mobile = customer.Mobile;
            order.Fax = customer.Fax;
            order.Email = customer.Email;
            order.CustomerID = customer.CustomerID;
            return order;
        }
        /// <summary>
        /// 分页获取数据源列表
        /// </summary>
        public DataSet GetList(int PageSize, int PageIndex, string OrderNo, string CreateDateFrom, string CreateDateTo, int TotalAmountStart, int TotalAmountEnd,
            int ContractStatus, string ShipAddress, string ItemCode, string BrandName, string Description, string CreatorWhere, int OrderType, int languageID
            )
        {
            return dal.GetList(PageSize, PageIndex,
        OrderNo, CreateDateFrom, CreateDateTo, TotalAmountStart, TotalAmountEnd,
         ContractStatus, ShipAddress, ItemCode, BrandName, Description, CreatorWhere, OrderType, languageID);
        }

        public DataSet GetOrderStatus(int languageID)
        {

            return dal.GetOrderStatus(languageID);
        }
        public string GetOrderStatusName(OrderStatus orderStatusID, int languageID)
        {
            return dal.GetOrderStatusName(orderStatusID, languageID);
        }


        /// <summary>
        /// copyorder到购物车
        /// </summary>
        /// <param name="orderID"></param>
        public void CopyOrder(string orderID, string userName)
        {
            OrderItemManager oim = new OrderItemManager();
            ShoppingCart sc = new ShoppingCart();
            ShoppingCartManager scm = new ShoppingCartManager();
            DataSet ds = oim.GetOrderItems(orderID);
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                sc.UserName = userName;
                sc.ProductID = Convert.ToInt32(dr["ProductID"].ToString());
                sc.Number = Convert.ToDecimal(dr["Quantity"]);
                scm.Add(sc);
            }
        }


        #endregion  成员方法

        public static bool CheckFrozen(bool Frozen, object FrozenFrom, object FrozenTo)
        {
            bool IsFrozen = true;
            if (Frozen)
            {
                if (FrozenFrom != null && FrozenFrom.ToString() != "")
                {
                    DateTime freezeFrom = Convert.ToDateTime(FrozenFrom);
                    if (freezeFrom > DateTime.Now)
                    {
                        IsFrozen = false;
                    }
                }
                if (FrozenTo != null && FrozenTo.ToString() != "")
                {
                    DateTime freezeTo = Convert.ToDateTime(FrozenTo);
                    if (freezeTo < DateTime.Now)
                    {
                        IsFrozen = false;
                    }
                }
            }
            else
            {
                IsFrozen = false;
            }
            return IsFrozen;
        }
        public int GetOrderCount(string username) {
         string sql  = "select  COUNT(1)  from  [Order]  where  Creator = '{0}'";
          object  obj = DbHelperSQL.GetSingle(string.Format(sql,username));

          if (null == obj) return 0;
          return  (int)obj;
        }

        public void ConfirmOrder(Order  Order )
        {
            //查看当前客户的帐号额度是否足够            !!!因为订单已经保存成功,已经把订单的金额累加到ECOrderSBalance中,所以此处只判断运费 by miao at  090204
            CustomerManager ctmM = new CustomerManager();
            TimKen.DataEntity.Customer customer = ctmM.GetModel(Order.CustomerID);
            decimal balance = customer.CreditLimit.Value + customer.CurrentAccountBalance.Value - customer.ECOrdersBalance.Value;
            //额度足够
            if (Order.Freight <= balance)
            {
                //设置状态为Pass
                Order.OrderStatus = OrderStatus.ConfirmPayment;


                //给对应的客户添加积分

                DataEntity.UserAccount userAccount = (new UserAccountManager()).GetModel(Order.Creator);

                if (null != userAccount)
                {
                    if (Order.Currency == "RMB" && SystemConfigManager.SystemConfig.AmountToPointsR != 0)
                        userAccount.Points += (int)Order.TotalAmount / SystemConfigManager.SystemConfig.AmountToPointsR;
                    else
                    {
                        if(SystemConfigManager.SystemConfig.AmountToPointsD != 0)
                        userAccount.Points += (int)Order.TotalAmount / SystemConfigManager.SystemConfig.AmountToPointsD;
                    }
                    (new UserAccountManager()).Update(userAccount);
                }
            }
            else
            { //额度不够
                //设置状态为for B1 Check
                Order.OrderStatus = OrderStatus.ConfirmPayment;
            }
            this.Update(Order);
            //更新客户的EC已用额度.加上当前订单的运费
            if (Order.Freight.HasValue)
            {
                customer.ECOrdersBalance = customer.ECOrdersBalance + Order.Freight;
                ctmM.Update(customer);
            }
        }

    }
}
